<?php

namespace Hangpu888\Hpadmin\utils\manager;

/**
 * @title 网络请求管理器
 * @desc 控制器描述
 * @author 楚羽幽 <admin@hangpu.net>
 */
class HttpManager
{
    /**
     * 发送GET请求
     *
     * @param string $url
     * @param array $data
     * @return array
     */
    public static function get(string $url, array $data = []): array
    {
        if ($data) {
            $params = http_build_query($data);
            $url = "{$url}?{$params}";
        }
        return self::send($url, [], 'GET');
    }

    /**
     * 发送POST请求
     *
     * @param string $url
     * @param array $data
     * @return array
     */
    public static function post(string $url, array $data): array
    {
        return self::send($url, $data, 'POST');
    }

    /**
     * 发送网络请求
     *
     * @param string $url
     * @param array $data
     * @param string $method
     * @return array
     */
    private static function send(string $url, array $data, string $method): array
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, count($data));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        return $output ? self::response($output) : [];
    }

    /**
     * 发送抖音POST
     *
     * @param string $url
     * @param array $data
     * @return void
     */
    public static function douyinPost(string $url,array $data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            return 'data is null';
        }
        if (is_array($data)) {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);

        // 转换结果集类型并返回
        return self::response($res);
    }

    /**
     * 转换请求后结果集
     *
     * @param string $data
     * @return array
     */
    private static function response(string $data): array
    {
        if ($data) {
            $data = json_decode($data, true);
        } else {
            $data = [];
        }
        return $data;
    }
}
